﻿using Sap.Contexts;
using Sap.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Sap.Repositories
{
    public class CategoryRepository
    {
        private DatabaseContext _db { get; set; }

        public CategoryRepository(DatabaseContext db)
        {
            _db = db;
        }

        public Category Get(int id)
        {
            return _db.Categories.SingleOrDefault(u => u.Id == id);
        }

        public IQueryable<Category> GetAll()
        {
            return _db.Categories;
        }

        public Category Add(Category user)
        {
            _db.Categories.Add(user);
            _db.SaveChanges();

            return user;
        }

        public Category Update(Category user)
        {
            _db.Entry(user).State = EntityState.Modified;
            _db.SaveChanges();

            return user;
        }

        public void Delete(int id)
        {
            var user = Get(id);
            _db.Categories.Remove(user);
        }

        public int GetPostPerCategory(int id)
        {
            return _db.Posts.Count(p => p.Category.Id == id);
        }
    }
}